package com.fingard.dsp.bank.directbank.ceb02.bankUtil;

import cebenc.softenc.SoftEnc;
import com.fingard.FGBiz;

import java.io.File;

public class MacUtil {
	/**
	 * 1.第三方发起密钥交换
	 * 2.第三方报文加MAC
	 * 3.第三方验MAC
	 */
	public static String updateKey(String xml,String args[]) {
			
		System.out.println( "**********更新密钥***开始**********");
		String mac = updateWorkKey(xml,args);
		System.out.println( "**********更新密钥***结束**********");
		return mac;
		
	}
	
	//更新密钥文件
	public static String updateWorkKey(String xml,String[] args) {
		//接收到的xml报文
		//例如     000540<?xml version="1.0" encoding="ISO-8859-1"?><out><head><Version>1.0.1</Version><InstId>BJCEB</InstId><AnsTranCode>BJCEBRWKRes</AnsTranCode><TrmSeqNum>admin180207110116</TrmSeqNum></head><tout><partnerCode>746</partnerCode><returnCode>00</returnCode><errorDescription></errorDescription><keyName>ZPK</keyName><keyValue>E5A915D81EB9B8BE816F4E46011B91C4</keyValue><verifyValue>032E5A89CDC16AE2</verifyValue><keyName1>ZAK</keyName1><keyValue1>D13A9DD478ABF1CB633DC4BAE1593CEA</keyValue1><verifyValue1>77F7AF1A9018A7F0</verifyValue1></tout></out>
		
		//获取报文中的keyValue、verifyValue标签中的值
		
		String keyValue = args[0];
		String verifyValue = args[1];
		System.out.println("keyValue:"+keyValue+",verifyValue:"+verifyValue);
		String mac = "";
		// 密钥文件目录"D:\\cebkey\\";
		//.0.SYS和.1.SYS为申请的主密钥文件，以下方法会生成.3.SYS，为工作密钥，即计算MAC所使用密钥
		String fileDir = FGBiz.DSPHOME_Parent+File.separator+"cebkey";
		System.out.println("密钥文件路径=====["+fileDir+"]");
		
		try {
			SoftEnc se = new SoftEnc();
			se.Init(fileDir+"\\");
			//将工作密钥更新到本地密钥文件中
			se.WriteMACK(keyValue,verifyValue);
			mac = se.GenMac(xml.getBytes("GBK"));
			System.out.println("工作密钥更新成功!!!!");			
		} catch (Exception e) {
			System.out.println("工作密钥更新失败!!!!");
			e.printStackTrace();
		}
		return mac;
	}
	
	
	public static String getMac(String xml) {
		SoftEnc st = new SoftEnc();
				
		String mac16 = "";
		try {
			mac16 = st.GenMac(xml.getBytes("GBK"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return mac16;
	}
	
}
